package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;


import view.GUI;

/**
 * This MouseAdapter implements the function for deleting or changing the coverimage
 * By rightclicking on the ImagePane a popupmenu comes up, where you can choose between
 * deleting and changing.
 *
 */
public class ImageCoverListener extends MouseAdapter {
	
	private GUI mainGUI;
	private ActionListener al;
	
	public ImageCoverListener(final GUI mainGUI) {
		
		this.mainGUI = mainGUI;
		
		//actionlistener for the menuitems in the popup
		al = new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {

				if(e.getActionCommand().equals("Coverbild entfernen")) {
					mainGUI.setImagePane();
				}
				if(e.getActionCommand().equals("Coverbild bearbeiten")) {
					
					final JFileChooser fc = new JFileChooser();
					//only JPEG and PNG
					fc.setAcceptAllFileFilterUsed(false);
					fc.setFileFilter(new FileFilter() {
						
						@Override
						public String getDescription() {
							return "jpeg,png";
						}
						
						@Override
						public boolean accept(File f) {
							if (f.isDirectory()) {
						        return true;
						    }
					        if (f.getName().toLowerCase().endsWith(".jpeg") ||
					        	f.getName().toLowerCase().endsWith(".jpg") ||
					        	f.getName().toLowerCase().endsWith(".png") ) {
						        	return true;
						    } else {
						    	return false;
						    }
						}
					});
					
					
					int returnVal = fc.showOpenDialog(mainGUI);
					
					if(returnVal == JFileChooser.APPROVE_OPTION) {
						File file = fc.getSelectedFile();
						
						try {
							BufferedImage image = ImageIO.read(file);
							mainGUI.setImagePane(image);
						}
						catch (IOException ex) {
							ex.printStackTrace();
							
						}
						
					}
				}
				
			}
		};
		
	}
	
	public ActionListener getAl() {
		return al;
	}
	
	@Override
	public void mousePressed(MouseEvent e) {
		maybeShowPopup(e);
	}
	
	@Override
	public void mouseReleased(MouseEvent e) {
		maybeShowPopup(e);
	}
	
	private void maybeShowPopup(MouseEvent e) {
		if(e.isPopupTrigger()) {
			mainGUI.getPopupMenu().show(e.getComponent(), e.getX(), e.getY());
		}
	}		
}
	
